﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Collections;
using System.Text.RegularExpressions;
using System.IO;
using log4net;
using System.Threading;
using System.Web;
using System.Web.UI.WebControls;

namespace Common
{
    public class FileHelper
    {
        private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        #region 获取模版
        /// <summary>
        /// 获取模版
        /// </summary>
        /// <param name="path">文件的路径</param>
        /// <param name="encoding">文件所使用的编码(ex:gbk|utf-8)</param>
        /// <returns></returns>
        public static string GetContentByFile(string path, string encoding)
        {
            if (File.Exists(path))
            {
                FileStream fs = File.Open(path, FileMode.Open);
                StreamReader sr = new StreamReader(fs, Encoding.GetEncoding(encoding));
                string result = sr.ReadToEnd();
                sr.Close();
                fs.Close();
                return result;
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 获取模版
        /// </summary>
        /// <param name="path">文件的路径</param>
        /// <returns></returns>
        public static string GetContentByFile(string path)
        {
            if (File.Exists(path))
            {
                FileStream fs = File.Open(path, FileMode.Open);
                StreamReader sr = new StreamReader(fs);
                string result = sr.ReadToEnd();
                sr.Close();
                fs.Close();
                return result;
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 获取模版
        /// </summary>
        /// <param name="path">文件的路径</param>
        /// <returns></returns>
        public static string[] GetContentLinesByFile(string path)
        {
            if (File.Exists(path))
            {
                return File.ReadAllLines(path);
            }
            else
            {
                return new string[] { "" };
            }
        }

        #endregion

        #region 生成文件
        /// <summary>
        /// 根据模板文件生成新的文件
        /// </summary>
        /// <param name="templatePath">模板文件路径</param>
        /// <param name="savePath">生成的文件路径</param>
        /// <param name="loopData">要循环列表的DataTable</param>
        /// <param name="otherData">要替换字符串的DataTable组合,一般为1行</param>
        public static void FileSaveByTemplateFile(string templatePath, string savePath, DataTable loopData, DataTable otherData, string coding)
        {
            string fileString = GetContentByFile(templatePath);
            FileSave(fileString, savePath, loopData, otherData, coding);
        }
        /// <summary>
        /// 根据模板文件生成新的文件
        /// </summary>
        /// <param name="templatePath">模板文件路径</param>
        /// <param name="savePath">生成的文件路径</param>
        /// <param name="loopData">要循环列表的DataTable</param>
        /// <param name="otherData">要替换字符串的DataTable组合,一般为1行</param>
        /// <param name="coding">编码格式</param>
        public static string FileSave(string templateString, string savePath, DataTable loopData, DataTable otherData, string coding)
        {
            if (otherData != null && otherData.Rows.Count > 0)
            {
                foreach (DataColumn otherKey in otherData.Columns)
                {
                    string key = otherKey.ColumnName;
                    templateString = templateString.Replace(string.Format("${0}$", key), otherData.Rows[0][key].ToString());
                }
            }
            RegexOptions myOption = RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline;
            Regex reg = new Regex("#loop(.+)#loop", myOption);
            string item = reg.Match(templateString).Groups[1].Value;
            if (!string.IsNullOrEmpty(item) && loopData != null && loopData.Rows.Count > 0)
            {
                StringBuilder sbBody = new StringBuilder();
                foreach (DataRow dr in loopData.Rows)
                {
                    string itemString = item;
                    foreach (DataColumn column in loopData.Columns)
                    {
                        Regex regColumn = new Regex(string.Format(@"\${0}\$", column.ColumnName), myOption);
                        itemString = regColumn.Replace(itemString, dr[column.ColumnName].ToString());
                    }
                    sbBody.Append(itemString);
                }
                templateString = reg.Replace(templateString, sbBody.ToString()).Replace("#loop", "");
            }

            CreateHTML(savePath, templateString, coding);
            return templateString;
        }
        #endregion

        #region 创建HTML文件
        /// <summary>
        /// 创建HTML文件
        /// </summary>
        /// <param name="path">文件所在路径</param>
        /// <param name="content">文件中的内容</param>
        /// <param name="coding">文件所使用的编码(ex:gbk|utf-8)</param>
        /// <returns></returns>
        public static void CreateHTML(string path, string content, string coding)
        {
            if (!File.Exists(path))
            {
                FileInfo fi = new FileInfo(path);
                if (!Directory.Exists(fi.DirectoryName))
                {
                    Directory.CreateDirectory(fi.DirectoryName);
                }
                FileStream rs = File.Create(path);
                System.IO.StreamWriter sw = new System.IO.StreamWriter(rs, System.Text.Encoding.GetEncoding(coding));
                sw.Write(content);
                sw.Close();
            }
            else
            {
                FileStream rs = File.Open(path, FileMode.Create);
                System.IO.StreamWriter sw = new System.IO.StreamWriter(rs, System.Text.Encoding.GetEncoding(coding));
                sw.Write(content);
                sw.Close();
            }
        }
        /// <summary>
        /// 创建HTML文件
        /// </summary>
        /// <param name="paths">文件所在路径(多路径的)</param>
        /// <param name="content">文件中的内容</param>
        /// <param name="coding">文件所使用的编码(ex:gbk|utf-8)</param>
        /// <returns></returns>
        public static void CreateHTML(string multiRoot, string subPath, string content, string coding)
        {
            string[] paths = BuildMultiPath(multiRoot, subPath);
            foreach (string path in paths)
            {
                if (!File.Exists(path))
                {
                    FileInfo fi = new FileInfo(path);
                    if (!Directory.Exists(fi.DirectoryName))
                    {
                        Directory.CreateDirectory(fi.DirectoryName);
                    }
                    FileStream rs = File.Create(path);
                    System.IO.StreamWriter sw = new System.IO.StreamWriter(rs, System.Text.Encoding.GetEncoding(coding));
                    sw.Write(content);
                    sw.Close();
                }
                else
                {
                    FileStream rs = File.Open(path, FileMode.Create);
                    System.IO.StreamWriter sw = new System.IO.StreamWriter(rs, System.Text.Encoding.GetEncoding(coding));
                    sw.Write(content);
                    sw.Close();
                }
            }
        }

        /// <summary>
        /// 构建多个路径
        /// </summary>
        /// <param name="multiRoot">多个根目录以,号分隔</param>
        /// <param name="subPath">子路径</param>
        /// <returns></returns>
        static string[] BuildMultiPath(string multiRoot, string subPath)
        {
            string[] multiPath = multiRoot.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < multiPath.Length; i++)
            {
                multiPath[i] = new StringBuilder().Append(multiPath[i]).Append(subPath).ToString();
            }
            return multiPath;
        }
        #endregion

        #region ** 文件属性操作 **
        /// <summary>
        /// 获取文件名
        /// </summary>
        public static string GetFileName(string filePath)
        {
            if (filePath.LastIndexOf(@"\") > 0)
            {
                return filePath.Substring(filePath.LastIndexOf(@"\") + 1);
            }
            else
            {
                return filePath;
            }
        }
        /// <summary>
        /// 获取后缀名 
        /// </summary>
        public static string GetSuffix(string filename)
        {
            int start = filename.LastIndexOf(".");
            int len = filename.Length;
            return filename.Substring(start, len - start);
        }

        /// <summary>
        /// 获取文件夹大小 : 返回M
        /// </summary>
        public static int GetDirLengthM(string absPath)
        {
            long bits = GetDirLength(absPath);
            long k = Convert.ToInt64(bits / 1024);
            int m = Convert.ToInt32(k / 1024);
            return m;
        }
        /// <summary>
        /// 获取文件夹大小 : 返回字节Bit
        /// </summary>
        public static long GetDirLength(string absPath)
        {
            try
            {
                string path = AbsPath(absPath);

                if (!Directory.Exists(path)) return 0;

                long len = 0;
                DirectoryInfo di = new DirectoryInfo(path);
                foreach (FileInfo fi in di.GetFiles())
                {
                    len += fi.Length;
                }
                DirectoryInfo[] dis = di.GetDirectories();
                if (dis.Length > 0)
                {
                    for (int i = 0; i < dis.Length; i++)
                    {
                        len += GetDirLength(dis[i].FullName);
                    }
                }
                return len;
            }
            catch (System.Exception ex)
            {
                Log.Error("Common.SysFile > GetDirLength() 出错\r\n" + ex.Message);
                throw new Exception(ex.Message);
            }
        }
        /// <summary>
        /// 获取文件详细属性 
        /// </summary>
        public static FileInfo GetFile(string filePath)
        {
            string path = AbsPath(filePath);
            return new FileInfo(path);
        }
        /// <summary>
        /// 判断文件是否存在
        /// </summary>
        public static bool Exists(string path)
        {
            return File.Exists(AbsPath(path));
        }
        /// <summary>
        /// 获取绝对路径
        /// </summary>
        public static string AbsPath(string path)
        {
            return (path.Contains(@":\")) ? path : System.Web.HttpContext.Current.Server.MapPath(EvalPath(path));
        }
        private static string EvalPath(string filePath)
        {
            if (filePath.Contains(@"\\")) filePath.Replace(@"\\", @"\");
            return filePath;
        }
        #endregion

        #region ** 内容(读写)操作 **
        /// <summary>
        /// 读取内容 （绝对路径）
        /// </summary>
        public static string Read(string absPath)
        {
            return Read(absPath, true);
        }
        public static string Read(string absPath, bool isCreate)
        {
            absPath = AbsPath(absPath);
            try
            {
                string s = "";
                if (!System.IO.File.Exists(absPath)) //如果文本文件不存在
                {
                    if (isCreate) CreateFile(absPath); //是否创建空白文件                    
                }
                else
                {
                    StreamReader f2 = new StreamReader(absPath, System.Text.Encoding.UTF8);
                    s = f2.ReadToEnd();
                    f2.Close();
                    f2.Dispose();
                }

                return s;
            }
            catch (System.Exception ex)
            {
                Log.Error("Common.SysFile > Read() 出错\r\n" + ex.Message);
                throw new Exception(ex.Message);
            }
        }
        /// <summary>
        /// 写入内容 (覆盖)
        /// </summary>
        public static void Write(string absPath, string text)
        {
            try
            {
                absPath = AbsPath(absPath);

                if (!System.IO.File.Exists(absPath)) CreateFile(absPath);

                HttpContext.Current.Application.Lock();
                System.IO.StreamWriter sw = new System.IO.StreamWriter(absPath, false, System.Text.Encoding.UTF8);
                sw.Write(text);
                sw.Close();
                sw.Dispose();
                HttpContext.Current.Application.UnLock();
            }
            catch (System.Exception ex)
            {
                Log.Error("Common.SysFile > Write() 出错\r\n" + ex.Message);
                throw new Exception(ex.Message);
            }
        }
        /// <summary>
        /// 写入内容 (追加)
        /// </summary>
        public static void Append(string absPath, string text)
        {
            try
            {
                absPath = AbsPath(absPath);
                if (!System.IO.File.Exists(absPath)) CreateFile(absPath);

                StreamWriter sw = File.AppendText(absPath);
                sw.Write(text);
                sw.Flush();
                sw.Close();
                sw.Dispose();
            }
            catch (System.Exception ex)
            {
                Log.Error("Common.SysFile > Append() 出错\r\n" + ex.Message);
                throw new Exception(ex.Message);
            }
        }
        #endregion

        #region ** 文件操作 **
        /// <summary>
        /// 创建空文件
        /// </summary>
        public static void CreateFile(string absPath)
        {
            try
            {
                absPath = AbsPath(absPath);
                FileInfo f = new FileInfo(absPath);
                if (!f.Exists)
                {
                    if (!f.Directory.Exists) f.Directory.Create(); //如果文件夹不存在则先创建文件夹

                    FileStream fs = f.Create();  //创建文件                   
                    fs.Close();
                }
            }
            catch (System.Exception ex)
            {
                Log.Error("Common.SysFile > CreateFile() 出错\r\n" + ex.Message);
                throw new Exception(ex.Message);
            }
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        public static bool UploadFile(HttpPostedFile pos, string path)
        {
            try
            {
                if (pos == null || pos.FileName == "") return false;
                else
                {
                    string fileName = pos.FileName;
                    string absPath = AbsPath(path);

                    if (System.IO.File.Exists(absPath + fileName))
                    {
                        fileName = "(new)" + fileName; // 如果文件名重复则重新命名
                    }

                    pos.SaveAs(absPath + fileName);

                    return true;
                }
            }
            catch (System.Exception ex)
            {
                Log.Error("Common.SysFile > UploadFile() 出错\r\n" + ex.Message);
                throw new Exception(ex.Message);
            }
        }


        /// <summary>
        /// 上传文件
        /// </summary>
        public static string UploadFileName(HttpPostedFile pos, string path, string FileName)
        {

            //if(pos==null)return"";


            //string fileName="";
            //if (!String.IsNullOrEmpty(pos.FileName))
            //{
            //    try
            //    {
            //    PicUpload picUp = new PicUpload();
            //    picUp.FileName = fileName + picUp.GetFileName();
            //    picUp.ImgPostFile = pos;
            //    fileName=picUp.FileName;
            //    pos.SaveAs(path);
            //    }
            //    catch (Exception  ex)
            //    {

            //        Log.Error("Common.SysFile > UploadFile() 出错\r\n" + ex.Message);
            //        throw new Exception(ex.Message);
            //    }

            //}
            //return fileName;
            try
            {
                if (pos == null || pos.FileName == "") return "";
                else
                {
                    string fileName = pos.FileName;
                    string absPath = AbsPath(path);

                    if (System.IO.File.Exists(absPath + fileName))
                    {
                        fileName = FileName + fileName; // 如果文件名重复则重新命名
                    }

                    pos.SaveAs(absPath + fileName);

                    return fileName;
                }
            }
            catch (System.Exception ex)
            {
                Log.Error("Common.SysFile > UploadFile() 出错\r\n" + ex.Message);
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        public static void DeleteFile(string filePath)
        {
            try
            {
                string path = AbsPath(filePath);
                if (File.Exists(path)) File.Delete(path);
            }
            catch (System.Exception ex)
            {
                Log.Error("Common.SysFile > DeleteFile() 出错\r\n" + ex.Message);
                throw new Exception(ex.Message);
            }
        }
        /// <summary>
        /// 拷贝文件
        /// </summary>
        public static void CoppyFile(string sourceFile, string newFile)
        {
            try
            {
                string sSource = AbsPath(sourceFile);
                string sNew = AbsPath(newFile);

                if (File.Exists(sSource)) File.Copy(sSource, sNew, true);
            }
            catch (System.Exception ex)
            {
                Log.Error("Common.SysFile > CoppyFile() 出错\r\n" + ex.Message);
                throw new Exception(ex.Message);
            }
        }
        /// <summary>
        /// 移动文件
        /// </summary>
        public static void MoveFile(string sourceFile, string newFile)
        {
            try
            {
                string sSource = AbsPath(sourceFile);
                string sNew = AbsPath(newFile);

                if (File.Exists(sSource)) File.Move(sSource, sNew);
            }
            catch (System.Exception ex)
            {
                Log.Error("Common.SysFile > MoveFile() 出错\r\n" + ex.Message);
                throw new Exception(ex.Message);
            }
        }
        #endregion

        #region ** 文件夹操作 **
        /// <summary>
        /// 创建文件夹
        /// </summary>
        public static void CreateFolder(string filePath)
        {
            try
            {
                // 判断目标目录是否存在如果不存在则新建之
                string path = AbsPath(filePath);
                if (!Directory.Exists(path)) Directory.CreateDirectory(path);
            }
            catch (System.Exception ex)
            {
                Log.Error("Common.SysFile > CreateFolder() 出错\r\n" + ex.Message);
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 删除文件夹
        /// </summary>
        public static void DeleteFolder(string filePath)
        {
            try
            {
                string path = AbsPath(filePath);

                if (Directory.Exists(path)) //如果存在这个文件夹删除之 
                {
                    foreach (string dir in Directory.GetFileSystemEntries(path))
                    {
                        if (File.Exists(dir))
                            File.Delete(dir);   //直接删除其中的文件                        
                        else
                            DeleteFolder(dir);  //递归删除子文件夹 
                    }

                    Directory.Delete(path, true); //删除已空文件夹                 
                }
            }
            catch (System.Exception ex)
            {
                Log.Error("Common.SysFile > DeleteFolder() 出错\r\n" + ex.Message);
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 拷贝文件夹 (包括所有内容) 果目标文件夹为只读属性就会报错
        /// </summary>
        public static void CopyFolder(string sourcePath, string targetPath)
        {
            string srcPath = AbsPath(sourcePath);
            string aimPath = AbsPath(targetPath);

            try
            {
                // 检查目标目录是否以目录分割字符结束如果不是则添加之
                if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
                    aimPath += Path.DirectorySeparatorChar;


                // 判断目标目录是否存在如果不存在则新建之
                if (!Directory.Exists(aimPath))
                    Directory.CreateDirectory(aimPath);


                // 得到源目录的文件列表，该里面是包含文件以及目录路径的一个数组
                //如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
                //string[] fileList = Directory.GetFiles(srcPath);
                string[] fileList = Directory.GetFileSystemEntries(srcPath);


                //遍历所有的文件和目录
                foreach (string file in fileList)
                {
                    //先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
                    if (Directory.Exists(file))
                        CopyFolder(file, aimPath + Path.GetFileName(file));
                    //否则直接Copy文件
                    else
                        File.Copy(file, aimPath + Path.GetFileName(file), true);
                }
            }
            catch (System.Exception ex)
            {
                Log.Error("Common.SysFile > CopyFolder() 出错\r\n" + ex.Message);
                throw new Exception(ex.Message);
            }
        }
        #endregion

        #region ** 绑定文件 **
        /// <summary>
        /// 获取目录下所有文件
        /// </summary>
        public static FileInfo[] GetAllFiles(string filePath)
        {
            try
            {
                string path = AbsPath(filePath);
                DirectoryInfo dirInfo = new DirectoryInfo(path);

                return dirInfo.GetFiles();
            }
            catch (System.Exception ex)
            {
                Log.Error("xxx 出错\r\n" + ex.Message);
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 绑定目录下的文件到Repeater
        /// </summary>
        public static void BindFiles(ref System.Web.UI.WebControls.Repeater repeater, string filePath)
        {
            repeater.DataSource = GetAllFiles(filePath);
            repeater.DataBind();
        }
        public static void BindFiles(ref System.Web.UI.WebControls.DataList datalist, string filePath)
        {
            datalist.DataSource = GetAllFiles(filePath);
            datalist.DataBind();
        }
        #endregion

        #region ** 文件下载 **
        /// <summary>
        /// 参数为虚拟路径
        /// </summary>
        public static string FileNameExtension(string FileName)
        {
            return System.IO.Path.GetExtension(MapPathFile(FileName));
        }
        /// <summary>
        /// 获取物理地址
        /// </summary>
        public static string MapPathFile(string FileName)
        {
            return HttpContext.Current.Server.MapPath(FileName);
        }
        /// <summary>
        /// 普通下载
        /// </summary>
        /// <param name="FileName">文件虚拟路径</param>
        public static void DownLoadold(string FileName)
        {
            string destFileName = MapPathFile(FileName);
            if (File.Exists(destFileName))
            {
                FileInfo fi = new FileInfo(destFileName);
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.ClearHeaders();
                HttpContext.Current.Response.Buffer = false;
                HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(Path.GetFileName(destFileName), System.Text.Encoding.UTF8));
                HttpContext.Current.Response.AppendHeader("Content-Length", fi.Length.ToString());
                HttpContext.Current.Response.ContentType = "application/octet-stream";
                HttpContext.Current.Response.WriteFile(destFileName);
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();
            }
        }
        /// <summary>
        /// 分块下载
        /// </summary>
        /// <param name="FileName">文件虚拟路径</param>
        public static void DownLoad(string FileName)
        {
            string filePath = MapPathFile(FileName);
            long chunkSize = 204800;             //指定块大小 
            byte[] buffer = new byte[chunkSize]; //建立一个200K的缓冲区 
            long dataToRead = 0;                 //已读的字节数   
            FileStream stream = null;
            try
            {
                //打开文件   
                stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                dataToRead = stream.Length;

                //添加Http头   
                HttpContext.Current.Response.ContentType = "application/octet-stream";
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachement;filename=" + HttpUtility.UrlEncode(Path.GetFileName(filePath)));
                HttpContext.Current.Response.AddHeader("Content-Length", dataToRead.ToString());

                while (dataToRead > 0)
                {
                    if (HttpContext.Current.Response.IsClientConnected)
                    {
                        int length = stream.Read(buffer, 0, Convert.ToInt32(chunkSize));
                        HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
                        HttpContext.Current.Response.Flush();
                        HttpContext.Current.Response.Clear();
                        dataToRead -= length;
                    }
                    else
                    {
                        dataToRead = -1; //防止client失去连接 
                    }
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("Error:" + ex.Message);
            }
            finally
            {
                if (stream != null) stream.Close();
                HttpContext.Current.Response.Close();
            }
        }
        /// <summary>
        ///  输出硬盘文件，提供下载 支持大文件、续传、速度限制、资源占用小
        /// </summary>
        /// <param name="_Request">Page.Request对象</param>
        /// <param name="_Response">Page.Response对象</param>
        /// <param name="_fileName">下载文件名</param>
        /// <param name="_fullPath">带文件名下载路径</param>
        /// <param name="_speed">每秒允许下载的字节数</param>
        /// <returns>返回是否成功</returns>
        //---------------------------------------------------------------------
        //调用：
        // string FullPath=Server.MapPath("count.txt");
        // ResponseFile(this.Request,this.Response,"count.txt",FullPath,100);
        //---------------------------------------------------------------------
        public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
        {
            try
            {
                FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                BinaryReader br = new BinaryReader(myFile);
                try
                {
                    _Response.AddHeader("Accept-Ranges", "bytes");
                    _Response.Buffer = false;

                    long fileLength = myFile.Length;
                    long startBytes = 0;
                    int pack = 10240;  //10K bytes
                    int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;

                    if (_Request.Headers["Range"] != null)
                    {
                        _Response.StatusCode = 206;
                        string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                        startBytes = Convert.ToInt64(range[1]);
                    }
                    _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                    if (startBytes != 0)
                    {
                        _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                    }

                    _Response.AddHeader("Connection", "Keep-Alive");
                    _Response.ContentType = "application/octet-stream";
                    _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));

                    br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                    int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;

                    for (int i = 0; i < maxCount; i++)
                    {
                        if (_Response.IsClientConnected)
                        {
                            _Response.BinaryWrite(br.ReadBytes(pack));
                            Thread.Sleep(sleep);
                        }
                        else
                        {
                            i = maxCount;
                        }
                    }
                }
                catch
                {
                    return false;
                }
                finally
                {
                    br.Close();
                    myFile.Close();
                }
            }
            catch
            {
                return false;
            }
            return true;
        }
        #endregion

        #region ** 文件上传 **
        /// <summary>
        /// 转换为字节数组
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns>字节数组</returns>
        public byte[] GetBinaryFile(string filename)
        {
            if (File.Exists(filename))
            {
                FileStream Fsm = null;
                try
                {
                    Fsm = File.OpenRead(filename);
                    return this.ConvertStreamToByteBuffer(Fsm);
                }
                catch
                {
                    return new byte[0];
                }
                finally
                {
                    Fsm.Close();
                }
            }
            else
            {
                return new byte[0];
            }
        }

        /// <summary>
        /// 流转化为字节数组
        /// </summary>
        /// <param name="theStream">流</param>
        /// <returns>字节数组</returns>
        public byte[] ConvertStreamToByteBuffer(System.IO.Stream theStream)
        {
            int bi;
            MemoryStream tempStream = new System.IO.MemoryStream();
            try
            {
                while ((bi = theStream.ReadByte()) != -1)
                {
                    tempStream.WriteByte(((byte)bi));
                }
                return tempStream.ToArray();
            }
            catch
            {
                return new byte[0];
            }
            finally
            {
                tempStream.Close();
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="PosPhotoUpload">控件</param>
        /// <param name="saveFileName">保存的文件名</param>
        /// <param name="imagePath">保存的文件路径</param>
        public string FileUpload(FileUpload PosPhotoUpload, string saveFileName, string imagePath)
        {
            string state = "";
            if (PosPhotoUpload.HasFile)
            {
                if (PosPhotoUpload.PostedFile.ContentLength / 1024 < 10240)
                {
                    string MimeType = PosPhotoUpload.PostedFile.ContentType;
                    if (String.Equals(MimeType, "image/gif") || String.Equals(MimeType, "image/pjpeg"))
                    {
                        string extFileString = System.IO.Path.GetExtension(PosPhotoUpload.PostedFile.FileName);
                        PosPhotoUpload.PostedFile.SaveAs(HttpContext.Current.Server.MapPath(imagePath));
                    }
                    else
                    {
                        state = "上传文件类型不正确";
                    }
                }
                else
                {
                    state = "上传文件不能大于10M";
                }
            }
            else
            {
                state = "没有上传文件";
            }
            return state;
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="binData">字节数组</param>
        /// <param name="fileName">文件名</param>
        /// <param name="fileType">文件类型</param>
        //-------------------调用----------------------
        //byte[] by = GetBinaryFile("E:\\Hello.txt");
        //this.SaveFile(by,"Hello",".txt");
        //---------------------------------------------
        public void SaveFile(byte[] binData, string fileName, string fileType)
        {
            FileStream fileStream = null;
            MemoryStream m = new MemoryStream(binData);
            try
            {
                string savePath = HttpContext.Current.Server.MapPath("~/File/");
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }
                string File = savePath + fileName + fileType;
                fileStream = new FileStream(File, FileMode.Create);
                m.WriteTo(fileStream);
            }
            finally
            {
                m.Close();
                fileStream.Close();
            }
        }
        #endregion


    }
}
